package com.mcppro.aidatabase.controller;

import com.mcppro.aidatabase.service.DatabaseOperationService;
import com.mcppro.aidatabase.service.SiliconFlowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统管理控制器
 * 
 * @author MCP Pro
 */
@RestController
@RequestMapping("/system")
@Slf4j
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:8081", "http://127.0.0.1:3000", "http://127.0.0.1:8081", "http://localhost", "http://127.0.0.1"}, 
             allowCredentials = "true", 
             maxAge = 3600)
public class SystemController {

    private final DatabaseOperationService databaseOperationService;
    private final SiliconFlowService siliconFlowService;

    @Autowired
    public SystemController(DatabaseOperationService databaseOperationService, 
                           SiliconFlowService siliconFlowService) {
        this.databaseOperationService = databaseOperationService;
        this.siliconFlowService = siliconFlowService;
    }

    /**
     * 系统健康检查
     */
    @GetMapping("/health")
    public Mono<ResponseEntity<Map<String, Object>>> healthCheck() {
        log.debug("执行系统健康检查");
        
        return siliconFlowService.testConnection()
                .map(aiConnected -> {
                    Map<String, Object> health = new HashMap<>();
                    health.put("status", "UP");
                    health.put("timestamp", System.currentTimeMillis());
                    
                    Map<String, Object> components = new HashMap<>();
                    
                    // 数据库连接检查
                    boolean dbConnected = databaseOperationService.testConnection();
                    components.put("database", Map.of(
                            "status", dbConnected ? "UP" : "DOWN",
                            "description", dbConnected ? "Database connection is healthy" : "Database connection failed"
                    ));
                    
                    // AI服务连接检查
                    components.put("ai_service", Map.of(
                            "status", aiConnected ? "UP" : "DOWN",
                            "description", aiConnected ? "AI service connection is healthy" : "AI service connection failed"
                    ));
                    
                    health.put("components", components);
                    
                    // 整体状态判断
                    boolean overallHealthy = dbConnected && aiConnected;
                    health.put("status", overallHealthy ? "UP" : "DOWN");
                    
                    return ResponseEntity.ok(health);
                })
                .onErrorResume(error -> {
                    log.error("健康检查失败", error);
                    Map<String, Object> health = new HashMap<>();
                    health.put("status", "DOWN");
                    health.put("timestamp", System.currentTimeMillis());
                    health.put("error", error.getMessage());
                    return Mono.just(ResponseEntity.internalServerError().body(health));
                });
    }

    /**
     * 获取数据库表结构
     */
    @GetMapping("/database/schema/{tableName}")
    public ResponseEntity<List<Map<String, Object>>> getTableSchema(@PathVariable String tableName) {
        log.debug("获取表结构 - 表名: {}", tableName);
        
        try {
            List<Map<String, Object>> schema = databaseOperationService.getTableSchema(tableName);
            return ResponseEntity.ok(schema);
        } catch (Exception e) {
            log.error("获取表结构失败 - 表名: {}", tableName, e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 测试数据库连接
     */
    @GetMapping("/database/test")
    public ResponseEntity<Map<String, Object>> testDatabaseConnection() {
        log.debug("测试数据库连接");
        
        Map<String, Object> result = new HashMap<>();
        try {
            boolean connected = databaseOperationService.testConnection();
            result.put("connected", connected);
            result.put("message", connected ? "数据库连接正常" : "数据库连接失败");
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("数据库连接测试失败", e);
            result.put("connected", false);
            result.put("message", "数据库连接测试异常: " + e.getMessage());
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 测试AI服务连接
     */
    @GetMapping("/ai/test")
    public Mono<ResponseEntity<Map<String, Object>>> testAiConnection() {
        log.debug("测试AI服务连接");
        
        return siliconFlowService.testConnection()
                .map(connected -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("connected", connected);
                    result.put("message", connected ? "AI服务连接正常" : "AI服务连接失败");
                    result.put("timestamp", System.currentTimeMillis());
                    
                    return ResponseEntity.ok(result);
                })
                .onErrorResume(error -> {
                    log.error("AI服务连接测试失败", error);
                    Map<String, Object> result = new HashMap<>();
                    result.put("connected", false);
                    result.put("message", "AI服务连接测试异常: " + error.getMessage());
                    result.put("timestamp", System.currentTimeMillis());
                    
                    return Mono.just(ResponseEntity.internalServerError().body(result));
                });
    }

    /**
     * 获取系统信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getSystemInfo() {
        log.debug("获取系统信息");
        
        Map<String, Object> info = new HashMap<>();
        info.put("application", "AI Database Manager");
        info.put("version", "1.0.0");
        info.put("description", "AI-powered database management system with natural language interface");
        info.put("java_version", System.getProperty("java.version"));
        info.put("spring_boot_version", "3.2.0");
        info.put("startup_time", System.currentTimeMillis());
        
        Runtime runtime = Runtime.getRuntime();
        Map<String, Object> memory = new HashMap<>();
        memory.put("max", runtime.maxMemory());
        memory.put("total", runtime.totalMemory());
        memory.put("free", runtime.freeMemory());
        memory.put("used", runtime.totalMemory() - runtime.freeMemory());
        info.put("memory", memory);
        
        return ResponseEntity.ok(info);
    }
}